var express = require('express');
const SMSClient = require('@alicloud/sms-sdk')
const tencentcloud = require("tencentcloud-sdk-nodejs-iai");
var jwt = require("jsonwebtoken")
const bcrypt = require('bcrypt')
var router = express.Router();
var { typeOneModel, userModel, typeTwoModel, BooksModel, historyModel, carlistModel } = require('../model/model');
let refreshTokens = [];


router.post('/register', async (req, res) => {
  let data = await userModel.find({ tel: req.body.tel })
  if (data.length > 0) {
    res.send({
      code: 400,
      msg: '该手机号已注册'
    })
  } else {
    req.body.img = ''
    const plaintextPassword = req.body.pwd; // 用户输入的密码
    const saltRounds = 10; // 盐值的轮数，推荐值为 10

    bcrypt.hash(plaintextPassword, saltRounds, (err, hash) => {
      if (err) {
        console.error('Error while hashing password:', err);
        // 处理错误情况
      } else {
        req.body.pwd = hash
        userModel.create(req.body)
        res.send({
          code: 200
        })
        // 将 hash 值存储到数据库中
        // 例如，将 hash 存储到用户的记录中
      }
    })
  }

})
router.post('/login', async (req, res) => {
  let data = await userModel.find({ tel: req.body.tel })
  if (data.length == 0) {
    res.send({
      code: 400,
      msg: '账号不存在'
    })
  } else {
    const hashedPasswordFromDatabase = data[0].pwd; // 从数据库中获取存储的哈希值
    bcrypt.compare(req.body.pwd, hashedPasswordFromDatabase, (err, result) => {
      if (err) {
        console.error('Error while comparing passwords:', err);
        // 处理错误情况
      } else if (result) {
        console.log('Passwords match!');
        let accessToken = jwt.sign({ tel: req.body.tel }, 'hjl', { expiresIn: '15m' })
        let refToken = jwt.sign({ tel: req.body.tel }, 'll')
        refreshTokens.push(refToken)
        console.log(refreshTokens, '登录');
        res.send({
          code: 200,
          accessToken,
          refToken,
          _id: data[0]._id
        })
        // 密码匹配，允许用户登录
      } else {
        console.log('Passwords do not match!');
        res.send({
          code: 401,
          msg: '密码错误'
        })
        // 密码不匹配，拒绝登录
      }
    });
  }

})
router.post('/loginY', async (req, res) => {
  console.log(req.body);
  let data = await userModel.find({ tel: req.body.tel })
  console.log(data);
  if (data.length == 0) {
    res.send({
      code: 400,
      msg: '账号不存在'
    })
  } else {
    let accessToken = jwt.sign({ tel: req.body.tel }, 'hjl', { expiresIn: '15m' })
    let refToken = jwt.sign({ tel: req.body.tel }, 'll')
    refreshTokens.push(refToken)
    res.send({
      code: 200,
      accessToken,
      refToken,
      _id: data[0]._id
    })
  }
  //验证码登录
})


router.post('/get_sms', function (req, res, next) {
  let phoneNum = req.body.tel;  //获取前端参数phone
  console.log("手机号码", phoneNum);

  //初始化sms_client
  let smsClient = new SMSClient({
    accessKeyId: 'LTAI5tQGQtjHJDj2usmzbFTs',  //accessKeyId 前面提到要准备的
    secretAccessKey: 'HNRphMsqf1fkutDPFu1zcML7AAOsl7'  //secretAccessKey 前面提到要准备的
  });

  let str = String(Math.random()).slice(-6)
  // 开始发送短信
  smsClient.sendSMS({
    PhoneNumbers: phoneNum,
    SignName: "二手平台", //签名名称 前面提到要准备的
    TemplateCode: "SMS_468985117", //模版CODE  前面提到要准备的
    TemplateParam: `{"code":'${str}'}`, // 短信模板变量对应的实际值，JSON格式
  }).then(result => {
    console.log("result", result)
    let { Code } = result;
    if (Code == 'OK') {
      res.json({
        code: 200,
        msg: 'success',
        sms: str
      })
      console.log(result)
    }
  }).catch(err => {
    console.log(err);
    res.json({
      code: 1,
      msg: 'fail: ' + err.data.Message
    })
  })

});


//人脸识别登录
router.post('/faceLogin', async (req, res) => {
  //获取前端传来的base64
  let b64 = req.body.b64

  const IaiClient = tencentcloud.iai.v20200303.Client;

  const clientConfig = {
    credential: {
      //自己的腾讯secretId
      secretId: "AKIDa6QXR7YmnaJvQA2lKgidT8d1DCzYu3zN",
      //自己的腾讯密匙
      secretKey: "HLBpGTSP9fx2tXx95oJaeV8XigQwGsYE",
    },
    region: "ap-beijing",  //地域参数（华北地区北京）
    profile: {
      httpProfile: {
        endpoint: "iai.tencentcloudapi.com",
      },
    },
  };

  const client = new IaiClient(clientConfig);

  const params = {
    "GroupIds": [  //你创建的人员库ID
      "Tiefsee0615"
    ],
    "Image": b64,  //图片的base64格式编码
    "NeedPersonInfo": 1,  //是否返回人员具体信息。0 为关闭，1 为开启。默认为 0。
    "QualityControl": 0,  //图片质量控制。 0: 不进行控制； 1:较低的质量要求
    "FaceMatchThreshold": 85,  //人脸对比度设置为大于85才可
  };

  let doc = await client.SearchFaces(params)

  //doc为人脸识别后的返回信息
  console.log(doc, 'doc');

  if (doc.Results[0].Candidates.length != 0) {  //表示当前人脸库有该人员
    let personName = doc.Results[0].Candidates[0].PersonName  //拿到该人员的名称
    console.log(personName, 'personName');
    console.log(doc.Results[0].Candidates[0]);
    let data = await userModel.find({ tel: String(personName) })
    //生成token
    let accessToken = jwt.sign({ tel: req.body.tel }, 'hjl', { expiresIn: '15m' })
    let refToken = jwt.sign({ tel: req.body.tel }, 'll')
    refreshTokens.push(refToken)
    res.send({
      code: 200,
      msg: "登录成功！",
      accessToken,
      refToken,
      tel: personName,
      _id: data[0]._id
    })

  } else {
    res.send({
      code: 401,
      msg: '人脸库无此人！'
    })
    return false
  }

})

router.put('/forget', async (req, res) => {
  let obj = req.body
  const plaintextPassword = obj.pwd; // 用户输入的密码
  const saltRounds = 10; // 盐值的轮数，推荐值为 10

  bcrypt.hash(plaintextPassword, saltRounds, async (err, hash) => {
    if (err) {
      console.error('Error while hashing password:', err);
      // 处理错误情况
    } else {
      obj.pwd = hash
      await userModel.updateOne({ tel: obj.tel }, obj)
      res.send({
        code: 200
      })
    }
  })
})

router.get('/hot', (req, res) => {
  if (req.header('Authorization')) {
    let token = req.header('Authorization').split(' ')[1]
    console.log(token);
    jwt.verify(token, 'hjl', async (err, decoded) => {
      if (err) {
        console.error('JWT verify error:', err);
        console.log(err.message);
        if (err.message == 'jwt expired') {
          res.send({
            status: 401,
            msg: 'token过期'
          })
        }
        // 处理验证失败的逻辑
      } else {
        const currentTimestamp = Math.floor(Date.now() / 1000);
        console.log(currentTimestamp);
        console.log(decoded.exp);
        if (decoded.exp < currentTimestamp) {
          // JWT 已过期
          res.send({
            status: 401,
            msg: 'token过期'
          })
          // 处理过期的逻辑
        } else {

          let data =await BooksModel.find()
          // console.log(data);
          res.send({
            code: 200,
            books: data
          })
        }
      }

    })
  }

})
router.get('/refreshToken', async (req, res) => {
  console.log(refreshTokens);
  // if (refreshTokens.includes(req.body.refreshToken)) {
  res.send({
    code: 200,
    newToken: jwt.sign({ tel: req.body.tel }, 'hjl', { expiresIn: '15m' })
  })
  // }
})
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;
